面向对象编程
self
-
类方法与普通函数只有一种特定的区别----前者必须有一个额外的名字,这个名字必须添加到参数列表的开头,但是你不用再调用这个功能时为这个参数赋值
-
按照惯例,它被赋予self这一名称
-
Sample Code:
class Person: def say_hi(self): print('say hi!!!'); p = Person(); p.say_hi();
init方法
- 会在类的对象被实例化时立即执行
- Sample Code:
class Person:
def __init__(self,name):
self.name = name;
def say_hi(self):
print('say hi!!! to',self.name);
p = Person("endian11");
p.say_hi();
类变量与对象变量
-
数据部分也就是字段,只不过是绑定到类与对象的命名空间。这就代表着这些名称仅在这些类与对象所存在的上下文中有效
-
字段有两种类型
- 类变量
- 类变量是共享的,它可以被属于该类的所有实例访问
- 对象变量
- 由类的每一个独立的对象或实例所拥有
- 类变量
-
Sample Code
class Robert: """表示有个带有名字的机器人.""" population = 0;#一个类变量,用来计数机器人的数量 def __init__(self,name): '''初始化数据''' self.name = name; print("(Initializing {})".format(self.name)); Robert.population +=1; def die(self): '''我挂了。。''' print('{} is beging destroyed!'.format(self.name)); Robert.population -=1; if Robert.population ==0: print('{} was the last one.'.format(self.name)); else: print("There are still {:d} roberts working.".format(Robert.population)); def say_hi(self): '''来自机器人的诚挚问候 没问题,你做的到。''' print("Greetings, my masters call me {}.".format(self.name)); @classmethod def how_many(cls): '''打印出当前的人口数量''' print("We have {:d} robots.".format(cls.population)); droid1 = Robert("R2-D2"); print(droid1.__init__.__doc__); droid1.say_hi(); Robert.how_many(); droid2 = Robert("c-3P0"); droid2.say_hi(); Robert.how_many(); print("\nRobots can do some work here.\n"); print("Robots have finished their work,so let us destroy them"); droid1.die(); droid2.die(); Robert.how_many();
-
运行结果:
(Initializing R2-D2) 初始化数据 Greetings, my masters call me R2-D2. We have 1 robots. (Initializing c-3P0) Greetings, my masters call me c-3P0. We have 2 robots. Robots can do some work here. Robots have finished their work,so let us destroy them R2-D2 is beging destroyed! There are still 1 roberts working. c-3P0 is beging destroyed! c-3P0 was the last one. We have 0 robots.
-
继承
-
面向对象编程的一大优点是对代码的重用
-
SampleCode:
class SchoolMember: '''代表学校里的成员。''' def __init__(self,name,age): self.name = name; self.age = age; print('(Initialized SchoolMember:{})'.format(self.name)); def tell(self): '''告诉我有关我的细节。''' print('Name:"{}" Age:"{}"'.format(self.name,self.age),end=" "); class Teacher(SchoolMember): '''代表一位老师。''' def __init__(self,name,age,salary): SchoolMember.__init__(self,name,age); self.salary = salary; print('Initialized Teacher:{}'.format(self.name)); def tell(self): SchoolMember.tell(self); print('Salary {:d}:'.format(self.salary)); class Student(SchoolMember): def __init__(self,name,age,marks): SchoolMember.__init__(self,name,age); self.marks = marks; print('Initialized Student:{}'.format(self.name)); def tell(self): SchoolMember.tell(self); print('Marks:"{:d}"'.format(self.marks)); t = Teacher("Li Zhanwei",28,25000); s = Student("Li Xiaolong",22,66); t.tell(); s.tell(); print(); members = {t,s}; for m in members: m.tell();
- 如果基类和子类都有相同的方法,python代码不会自动调用基类的函数,需要自己显式地调用
网友评论