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>
[email protected]
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__)
[email protected]
Patrick Hua
100000
104000
{'pay': 104000, 'last': 'Hua', 'email': '[email protected]', 'first': 'Patrick'}
{'__module__': '__main__', '__init__': , 'raise_amount': 1.04, 'fullname': , '__doc__': None, 'apply_raise': }
1.99
1.99
{'pay': 104000, 'raise_amount': 2, 'last': 'Hua', 'email': '[email protected]', '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))
[email protected]
('-->', 'Patrick Hua')
('-->', 'Andrew Ng')
True
True
True
True
[Finished in 0.0s]

你可能感兴趣的:(python class)