python class

class Emp:
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.mail = first + '.' + last + '@company.com'
    def full_name(self):
        return '{} {}'.format(self.first,self.last)
    def getby(self):
        pass
emp1 = Emp('Patrick', 'Hua', 10000,)
print(emp1)
print(emp1.mail)
print(emp1.full_name())
print(Emp.full_name(emp1))
print(emp1.getby())
<__main__.Emp instance at 0x106580ab8>
Patrick.Hua@company.com
Patrick Hua
Patrick Hua
None
[Finished in 0.0s]
class fruits:
    def __init__(self, apple, orange, peach):
        self.apple = apple
        self.orange = orange
        self.peach = peach
        self.all = apple + orange + peach
    def sum(self):
        return self.apple + self.orange + self.peach
f1 = fruits(1,2,3)
print(f1.all)
print(f1.sum())
6
6

instance variables and class variables


class Employee:
    raise_amount = 1.04
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'
    def fullname(self):
        # return self.first + ' ' + self.last
        return '{} {}'.format(self.first, self.last)
    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amount)
        # Employee.raise_amount will work

emp1 = Employee('Patrick', 'Hua', 100000)
print(emp1.email)
print(Employee.fullname(emp1))
print(emp1.pay)
emp1.apply_raise()
print(emp1.pay)


print(emp1.__dict__) # show namespace of emp1
print(Employee.__dict__)

Employee.raise_amount = 1.99

print(Employee.raise_amount)
print(emp1.raise_amount)
emp1.raise_amount = 2 # it creates the raise_amount attribute in emp1
print(emp1.__dict__)
Patrick.Hua@company.com
Patrick Hua
100000
104000
{'pay': 104000, 'last': 'Hua', 'email': 'Patrick.Hua@company.com', 'first': 'Patrick'}
{'__module__': '__main__', '__init__': <function __init__ at 0x107eaeb90>, 'raise_amount': 1.04, 'fullname': <function fullname at 0x107eaec08>, '__doc__': None, 'apply_raise': <function apply_raise at 0x107eaec80>}
1.99
1.99
{'pay': 104000, 'raise_amount': 2, 'last': 'Hua', 'email': 'Patrick.Hua@company.com', 'first': 'Patrick'}
[Finished in 0.0s]

class Employee:
    raise_amount = 1.04
    emp_cnt = 0
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'
        Employee.emp_cnt += 1
        # self.emp_cnt += 1 won't work, self.raise_amount works, think about why?
    def fullname(self):
        # return self.first + ' ' + self.last
        return '{} {}'.format(self.first, self.last)
    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amount)
        # Employee.raise_amount will work

emp1 = Employee('Patrick', 'Hua', 100000)
print(Employee.emp_cnt)


'''
in or out of the class, there are two ways to call class variables
the first, self.raise_amount, this changes only emp1
the second, Employee.raise_amount, this changes all the emps
these two methods are the same if not to change variables
'''

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

# class method
# static method

class Employee:
    num_of_emps = 0
    raise_amt = 1.04
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.email = first + '_' + last + '@email.com'
        self.pay = pay
        Employee.num_of_emps += 1
    def fullname(self):
        return '{} {}'.format(self.first, self.last)
    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)
    @classmethod
    def set_raise_amt(cls, amount):
        cls.raise_amt = amount
    @classmethod
    def from_string(cls, emp_str):
        first, last, pay = emp_str.split('-')
        return cls(first, last, pay)
    @staticmethod
    def is_workday(day):
        if day.weekday() == 5 or day.weekday() == 6:
            return False
        return True

emp1 = Employee('Patrick', 'Hua', 100000)
emp2 = Employee('Andrew', 'Ng', 100000)
Employee.set_raise_amt(1.05)
print(emp1.raise_amt)
print(emp2.raise_amt)
first, last, pay = 'John-Doe-70000'.split('-')
emp3 = Employee(first, last, pay )
emp4 = Employee.from_string('John-Doe-70000')
# instances and class are different, sometime you want to do sth. about the class within this class/instance
import datetime
this_day = datetime.date(2017, 12, 5)
print(Employee.is_workday(this_day))
# you want to build a function within the class without calling instance or class
1.05
1.05
True
[Finished in 0.0s]
# inheritance - creating subclasses

class Employee(object):
    num_of_emps = 0
    raise_amt = 1.04
    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.email = first + '_' + last + '@email.com'
        self.pay = pay
        Employee.num_of_emps += 1
    def fullname(self):
        return '{} {}'.format(self.first, self.last)
    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)
class Developer(Employee):
    raise_amt = 2
    def __init__(self, first, last, pay, language):
        super(Developer, self).__init__(first, last, pay)
        self.language = language
class Manager(Employee):
    def __init__(self, first, last, pay, employees = None):
        super(Manager, self).__init__(first, last, pay)
        if employees is None:
            self.employees = []
        else:
            self.employees = employees
    def add_emp(self, emp):
        if emp not in self.employees:
            self.employees.append(emp)
    def remove_emp(self, emp):
        if emp in self.employees:
            self.employees.remove(emp)
    def print_emps(self):
        for emp in self.employees:
            print('-->', emp.fullname())

emp1 = Employee('Patrick', 'Hua', 100000)
emp2 = Employee('Andrew', 'Ng', 100000)
dev1 = Developer('Patrick', 'Hua', 100000, 'python')
magr = Manager('Sue', 'Smith', 900000, [dev1])
# print(help(Developer))
print(magr.email)
magr.add_emp(emp1)
magr.add_emp(emp2)
magr.remove_emp(emp1)
magr.print_emps()

print(isinstance(magr, Manager))
print(isinstance(magr, Employee))
print(issubclass(Developer, Employee))
print(issubclass(Manager, Employee))
Sue_Smith@email.com
('-->', 'Patrick Hua')
('-->', 'Andrew Ng')
True
True
True
True
[Finished in 0.0s]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,569评论 0 23
  • 上个周末大学同学聚会,又有一位要回武汉了,回去的理由大同小异,在深圳待够了,在武汉找了个公司,准备回武汉买房养老。...
    Sosofunny阅读 4,562评论 10 16
  • 今天晚上因要参加培训,下班到家后匆匆的吃了晚饭,开车就走了,全然没发现欣翼书包落在车后排上,还好作业在托辅...
    欣翼妈妈阅读 213评论 1 2
  • 1.我们属于端内业务2.POI详情页为搜索线,剩下的是基础地图&生活服务线。
    以然以然阅读 211评论 0 0

友情链接更多精彩内容