python note 20 (object oriented course 2)

Content today

  • Class member
  • member qualifier character

Content review & Supplement

  1. Three characteristics

    • encapsulation

      • Function encapsulation to class

      • Data encapsulation to objects*

        class Foo:
            def __init__(self,name,age):
                self.name = name
                self.age = age
        
        obj = Foo('alex',19)
    • inherit

    • polymorphic

Detailed content

1. member

  • class
    • Class variables
    • Binding method
    • Class method
    • Static method
    • attribute
  • Instance (object)
    • Instance variables

1.1 instance variable

class Foo:
    def __init__(self,name):
        self.name=name
    def func(self):
        print(self.name)

obj1=Foo('ALEX')
obj1.func()
obj2=Foo('ERIC')
obj2.func()

1.2 variables

class Foo:
    city='Wuhan'
    def __init__(self,name):
        self.name=name
    def func(self):
        pass
obj1=Foo('ALEX')
print(obj1.name)
print(obj1.city)
print(Foo.city)
obj2=Foo('ERIC')
print(obj2.name)
print(obj2.city)
print(Foo.city)

ALEX
//Wuhan
//Wuhan
ERIC
//Wuhan
//Wuhan
  • Definition: write at the next level of the class and at the same level as the method.

  • Visit:

    Class. Class variable name
     Object. Class variable name
  • Interview questions

    class Base:
        x = 1  
    obj = Base()
    print(obj.x) # First go to the object, not to the class.
    obj.y = 123  # A variable of y=123 is added to the object. Cannot modify in class.
    print(obj.y)
    obj.x = 123#Add x=123 to the object, and X in the class is still = = 1.
    print(obj.x)#Print x==123 in the object.
    print(Base.x)#It prints x==1 in the class.
    #First look for variables in objects, then in classes.
    class Parent:
        x = 1
    
    class Child1(Parent):
        pass
    
    class Child2(Parent):
        pass
    
    print(Parent.x,Child1.x,Child2.x) # 1 1 1
    Child1.x = 2
    print(Parent.x,Child1.x,Child2.x) # 1 2 1
    Child2.x = 3
    print(Parent.x,Child1.x,Child2.x) # 1 2 3

Summary: find variables first. You don't find classes or base classes. You can only modify or assign values in your own internal settings.

class Foo:
    x=1
class Parent(Foo):
    pass
obj=Parent()
print(obj.x)
obj.x=2
print(Parent.x)
print(obj.x)

1
1
2

1.3 method (binding method / common method)

  • Definition: at least one self parameter
  • Execute: first create the object, which is created by the object. Method ().
class Foo:
    def func(self,a,b):
        print(a,b)
        
obj = Foo()
obj.func(1,2)
# ###########################
class Foo:
    def __init__(self):
        self.name = 123

    def func(self, a, b):
        print(self.name, a, b)

obj = Foo()
obj.func(1, 2)

1.4 static method

  • Definition:
    • @Static method decorator
    • Unlimited parameters
  • Implementation:
    • Class. Static method name ()
    • Object. Static method () (not recommended)
class Foo:
    def __init__(self):
        self.name = 123

    def func(self, a, b):
        print(self.name, a, b)

    @staticmethod
    def f1():
        print(123)

obj = Foo()
obj.func(1, 2)

Foo.f1()
obj.f1() # Not recommended

Category 1.5 method

  • Definition:
    • @classmethod decorator
    • At least cls parameter, current class.
  • Implementation:
    • Class. Class method ()
    • Object. Class method () (not recommended)
class Foo:
    def __init__(self):
        self.name = 123

    def func(self, a, b):
        print(self.name, a, b)

    @staticmethod
    def f1():
        print(123)

    @classmethod
    def f2(cls,a,b):
        print('cls Is the current class.',cls)
        print(a,b)

obj = Foo()
obj.func(1, 2)

Foo.f1()
Foo.f2(1,2)

Interview questions:

#Question: what's the difference between @ classmethod and @ static method?
"""
One is a static method. 
Definition:
    Class method: use @ classmethod as the decorator with at least one cls parameter.
    Static method: static method is used as decorator with unlimited parameters.
Call:
    Class. Method.
    Object. Method can also be called. 
"""

1.6 attribute

  • Definition:
    • @property decorator
    • Only one self parameter
  • Implementation:
    • Object. Method without parenthesis.
class Foo:

    @property
    def func(self):
        print(123)
        return 666

obj = Foo()
result = obj.func
print(result)
# Application of attributes

class Page:
    def __init__(self, total_count, current_page, per_page_count=10):
        self.total_count = total_count
        self.per_page_count = per_page_count
        self.current_page = current_page
    @property
    def start_index(self):
        return (self.current_page - 1) * self.per_page_count
    @property
    def end_index(self):
        return self.current_page * self.per_page_count


USER_LIST = []
for i in range(321):
    USER_LIST.append('alex-%s' % (i,))

# Please implement pagination display:
current_page = int(input('Please enter the page number to view:'))
p = Page(321, current_page)
data_list = USER_LIST[p.start_index:p.end_index]#The brackets in p.start_index() are omitted.
for item in data_list:
    print(item)

2. Member modifier

  • Publicly owned, accessible everywhere.
  • Private. Only you can access it.
class Foo:
    def __init__(self, name):
        self.__name = name

    def func(self):
        print(self.__name)


obj = Foo('alex')
# print(obj.__name)#Object obj is external and cannot be accessed externally. So the output here is wrong.
obj.func()#Here obj calls the method, which prints out the private variables.
class Foo:
    __x = 1

    @staticmethod
    def func():
        print(Foo.__x)


# print(Foo.__x)
Foo.func()
class Foo:
    def __init__(self,name):
        self.__x=name

    def __fun(self):
        print('msg')

    def show(self):
        self.__fun()

obj = Foo()
# obj.__fun()#A child class cannot access private things in the parent class.
#py Back door, if forced to access. print(obj._Foo__x)#Free part.
obj.show()

#As long as the double underline is added in front, it will become private. Private can only be used internally, and external calls such as direct object calls are not allowed.

3. supplement

class Foo:
    def __init__(self,num):
        self.num = num
        
        
cls_list = []
for i in range(10):
    cls_list.append(Foo)
    
for i in range(len(cls_list)):
    obj = cls_list[i](i)
    print(obj.num)
class Foo:
    def __init__(self,num):
        self.num = num
        
B = Foo
obj = B('alex')
class Foo:
    def f1(self):
        print('f1')
    
    def f2(self):
        print('f2')

obj = Foo()

v = [ obj.f1,obj.f2 ]
for item in v:
    item()
class Foo:
    def f1(self):
        print('f1')
    
    def f2(self):
        print('f2')
        
    def f3(self):
        v = [self.f1 , self.f2 ]
        for item in v:
            item()
            
obj = Foo()
obj.f3()
class Account:
    
    def login(self):
        pass
    
    def register(self):
        pass
    
    def run(self):
        info = {'1':self.register, '2':self.login }
        choice = input('Please choose:')
        method = info.get(choice)
        method()
class Foo:
    pass

class Foo(object):
    pass

# In Python 3, the two methods are the same, because all classes inherit the object class by default, and all are new classes.

# If it is defined in python2, it is called: Classic class
class Foo:
    pass 
# If it is defined in python2, it is called: new class
class Foo(object):
    pass 

class Base(object):
    pass
class Bar(Base):
    pass
# Enforce access to private members

class Foo:
    def __init__(self,name):
        self.__x = name


obj = Foo('alex')

print(obj._Foo__x) # Force access to private instance variables

summary

  1. Data encapsulation

  2. Search for inheritance relationship

  3. nesting

    class School(object):
        def __init__(self,title,addr):
            self.title = title
            self.address = addr
    
    class ClassRoom(object):
    
        def __init__(self,name,school_object):
            self.name = name
            self.school = school_object
    
    s1 = School('Beijing','Shahe')
    s2 = School('Shanghai','Pudong')
    s3 = School('Shenzhen','Nanshan')
    
    c1 = ClassRoom('Full stack 21 phase',s1)
    c1.name
    c1.school.title
    c1.school.address
    # ############################################
    v = [11,22,33,{'name':'Mountain and sea','addr':'Pudong'}]
    
    v[0]
    v[3]['name']
    

Tags: Python Attribute

Posted on Mon, 17 Feb 2020 04:06:30 -0500 by donbueck