码迷,mamicode.com
首页 > 其他好文 > 详细

类初试

时间:2018-02-24 19:32:06      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:python3.0   tac   self   fun   gpo   attribute   pytho   can   div   

在模块或者脚本开始的地方放置赋值语句 _metaclass_=type  ,

在python3.0中 不存在旧式类,也就不用加上赋值语句。

定义一个新式类 (旧式类没有 ()   )请尽量使用新式类

1 class Person():#新式类
2     def setName(self,name):
3         self.name=name
4     def getName(self):
5         return self.name
6 def getCharacter(self,character):
7        self.character=character
8   def __character(self):
9       return self.character
10 def greet(self): 11 print("hello , I‘m %s" %(self.name))

操作:

1 >>> foo=Person()
2 >>> bar=Person()
3 >>> foo.setName(Sally)
4 >>> bar.setName(Marry)
5 >>> foo.greet()
6 hello , Im Sally
7 >>> bar.greet()
8 hello , Im Marry

对 self 的解释:

1 >>> foo.name
2 Sally
3 >>> bar.name
4 Marry 

self 是对于对象自身的引用(命名为 self 是约定成俗)

类的私有成员:

Person() 内的函数 __character(self) 是其私有成员

1 >>>foo.getCharacter(‘fooish‘)
2
>>> foo.character 3 fooish 4 >>> foo.__character() 5 Traceback (most recent call last): 6 File "<pyshell#19>", line 1, in <module> 7 foo.__character() 8 AttributeError: Person object has no attribute __character 9 >>> foo._Person__character() 10 fooish

继承:

比如 每只鸟都是” 鸟类 “的实例 ,“ 企鹅类”是“ 鸟类 ”的子类 ,” 鸟类 “则是“ 企鹅类 ” 的超类

1 class Bird():
2         song=Squaawk
3         fly_style=Glide
4         def sing(self):
5              print(self.song)
6         def fly(self ):
7             print(self.fly_style)
8 class Penguin(Bird):
9         pass

Penguin() 继承了 Bird() 所有内容

 1 >>> bird=Bird()
 2 >>> bird.sing()
 3 Squaawk
 4 >>> bird.fly()
 5 Glide
 6 >>> penguin=Penguin()
 7 >>> penguin.sing()
 8 Squaawk
 9 >>> penguin.fly()
10 Glide

但 企鹅是不会飞的 ,所以我们需要重写 fly() 或者在 Penguin() 内不使用 fly()

1 class Penguin(Bird):
2         def fly(self):
3             print("can‘t fly")
1 >>> penguin=Penguin()
2 >>> penguin.fly()
3 cant fly

绑定:

 1 class Class():
 2     def method(self):
 3         print(I have a apple)
 4 
 5 def function():
 6     print("I don‘t ... ")
 7 
 8 >>> instance=Class()
 9 >>> instance.method()
10 I have a apple
11 >>> instance.method=function
12 >>> instance.method()
13 I dont ... 

 

类初试

标签:python3.0   tac   self   fun   gpo   attribute   pytho   can   div   

原文地址:https://www.cnblogs.com/Sky-Aces/p/8467162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!