Defining a class immediately triggers the execution of the class body code, resulting in a namespace
class Oldboyschool: ' Oldboy ' def Choose_course (self): Print ('ischoosing course')
Accessing the properties of a class
Print (Oldboyschool.school)
The method of accessing the class, the class method is the ordinary method
Print (Oldboyschool.choose_course ('123'))
STU1 == oldboyschool ()# all objects and class variables have the same memory address as print(ID (stu1.school), ID (Stu2.school), ID (oldboyschool.school))
#对象的绑定方法地址一样, the object and class are not the same as the method address print(ID (stu1.choose_course), id (stu2.choose_course), ID ( Oldboyschool.choose_course)) #2289801247880 2289801247880 2289804409440
Redefine a class
classOldboyschool2:school='Oldboy'#automatically start execution when invoking a classSTU1def __init__(self, name, age, Sex): Self.name= Name#Stu1.nameSelf.age =Age Self.sex=SexdefChoose_course (self):Print('%s is choosing course'%self.name)
Two things happen to the calling class
1. An empty object is generated
2. It will trigger the operation of the __INIT__ function in the class, passing the empty object together with the parameters in parentheses.
STU1 = OldBoySchool2 ("Jack""male"= OldBoySchool2 ("Tom""female")
Own unique properties exist in the object namespace
Print (STU1. __dict__) # {' name ': ' Jack ', ' age ':, ' sex ': ' Male '} Print (STU2. __dict__) # {' name ': ' Tom ', ' age ': +, ' sex ': ' Female '}
First look in your own namespace, then go to the class namespace.
Print # your own namespace Print # namespace of the class
The data properties of a class are shared with all objects, and everyone's memory addresses are the same
Print (ID (stu1.school)) Print (ID (oldboyschool2.school))
Equivalent to STU1 adds a school property that does not affect the class's properties
' XXX '
A function defined in a class is used to bind to an object, called a binding method
With the original function need to pass their own objects, more trouble, so with the binding method, you do not have to preach their own objects
Print (ID (oldboyschool2.choose_course)) # 2492997074320 Print (ID (stu1.choose_course)) # 2492993911944 Print (ID (stu2.choose_course)) # 2492993911944
Calling methods
# Jack is choosing course # Tom is choosing course
Object-oriented examples:
classMysql:def __init__(self, host, port, DB, CharSet): Self.host=host Self.port=Port Self.db=DB Self.charset=CharSetdefexc1 (Self, SQL): Conn=Connect (self.host, Self.port, Self.db, Self.charset) conn.execute (SQL)returnXXXdefExc2 (Self, proc_name): Conn=Connect (self.host, Self.port, Self.db, Self.charset) Conn.call_proc (proc_name)returnXxxobj=mysql ('1.1.1.1', 3306,'DB1','Utf-8') Obj.exc1 ('select * Froom xxx') Obj.exc2 ('P1')
Python learning 7_1 Object-oriented basic concepts and usage