Having studied C + + for a while, and have some knowledge of object-oriented, now learn about object-oriented through Python:
Class
Class is created using the class keyword. The fields and methods of the class are listed in an indent block.
class Person : Pass #pass语句表示一个空类 = Person ()print(p) $ python simplestclass.py<__main__. Person object at 0x019f85f0>
Methods of the Object
class Person : def Sayhi (self): # I have self when I define a function. Print ('Hello, how is it? ' = Person () p.sayhi ()# This short example can also is written as person (). Sayhi ()
__init__ method
The beginning and end of this name are double underlines
(It feels like a constructor in C + +)
class Person : def __init__ (self, name): = name def Sayhi (self): print(' Hello ', my name is ', self.name) = person ('swaroop')
When an object is created, the function runs immediately.
Class and Object variables
Just like static variables and instance variables in C + +, it's a good idea to look directly at one of the simple examples I wrote:
#Filename:claaorinsvarclassanimal:population=0def __init__(self,name): Self.name=name Animal.population+ = 1defSayhi (self):Print("My name is"+self.name)defHowmany ():#This function does not pass arguments to self #print (' We have ' + animal.population + ' animals ') #use the above code after the program error "Print (' We have ' + animal.population + ' animals ') #Typeerror:must is str, not int " #Animal.population cannot automatically connect to strings, and in Java it can be automatically promoted with expressions, but not in Python . Print('We have {0} animals.'. Format (animal.population)) An1= Animal ('DOGWW') An1.sayhi () an2= Animal ('CATMM') An2.sayhi () Animal.howmany ()
Inherited
classSchoolmenber:def __init__(self,name,age): Self.name=name Self.age= AgedefTell (self):Print('name:{0} age:{1}'. Format (self.name,self.age))classTeacher (schoolmenber):def __init__(self,name,age,salary): Schoolmenber.__init__(Self,name,age)#don't forget to write the self here .Self.salary =SalarydefTell (self): Schoolmenber.tell (self)Print('salary: {0}'. Format (self.salary))classStudent (schoolmenber):def __init__(Self,name,age,mark): Schoolmenber.__init__(self,name,age) Self.mark=MarkdefTell (self): Schoolmenber.tell (self)Print('mark:{0}'. Format (self.mark)) Stu= Student ('Jenny', 20,95) Tec= Teacher ('Mary', 50,5000) Menbers=[Stu,tec] forMenberinchMenbers:menber.tell ()
Start learning Python object-oriented programming