频道栏目
首页 > 资讯 > Python > 正文

Python Base Five介绍

17-11-17        来源:[db:作者]  
收藏   我要投稿

Python Base Five

// 8 day(2016/8/11)

38. In python , it is oop.

class Baskball:
def setName(self, name):
self.name = name
def kick(self):
print('my name is %s' % self.name)
baskball = Baskball()
baskball.setName('baskball')
baskball.kick()

-> my name is baskball

class Ball:
def __init__(self, name):
self.name = name
def kick(self):
print('my name is %s' % self.name)
b = Ball('tom')
b.kick()

-> my name is tom

 

39. In python ,how to define private variable,

such as:

class Person:
name = 'roy'
p = Person()
print(p.name)

-> roy

if you use:

class Person:
__name = 'roy'
p = Person()
print(p.__name) || print(p.name)

-> error

if you use __ before variable ,you can access it direct.

class Person:
__name = 'roy'
def getName(self):
return self.__name
p = Person()
print(p.getName())

-> roy

class Person:
__name = 'roy'
p = Person()
print(p._Person__name)

-> roy

 

40. inheritance mechanism

class SubClassName:(ParentClassName):

……

class Parent:
def hello(self):
print('write code change world')

class Child(Parent):
pass

p = Parent()
p.hello()

c = Child()
c.hello()

->

write code change world

write code change world

if subclass methon is same with parent , it will cover parent method, such as:

class Child(Parent):

def hello(self):

print('believe youself')

c = Child()

c.hello()

-> believe youself

now we will study a simple example:

import random as r
class Fish:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
self.x -= 1
print('my position is:',self.x, self.y)
 

class Shark(Fish):
def __init__(self):
#Fish.__init__(self)
super().__init__()
self.hungry = True

def eat(self):
if self.hungry:
print('eat eat eat')
self.hungry = False
else:
print('not hungry')
 

1,Fish.__init__(self)
2,super().__init__()

1 and 2 is same ,if you not add this ,you invoke move in Shark ,it will error, because ,__init__ will cover parent method, you call move() ,it will not found x and y. if you use 1 and 2, it will solve this question

multiply parent class:

class subClassName:(parent1ClassName, parent2ClassName):

……


class Base1:
def fool1(self):
print('it is fool1')

class Base2:
def fool2(self):
print('it is fool2')

class c(Base1, Base2):
pass

c = c()
c.fool1()
c.fool2()

-> it is fool1

-> it is fool2

 

相关TAG标签
上一篇:“无现金”或成推动经济社会转型力量
下一篇:win10安装双系统后设置开机默认优先启动系统的方法
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站