昨天的self _init_(self,param1,param2)问题
class Ball:
def setName(tt,name):
tt.name=name
def kick(tt):
print('我是%s,该死的,谁踢我...'%tt.name)
a=Ball()
a.setName('球A')
b=Ball()
b.setName('球B')
c=Ball()
c.setName('球C')
a.kick()
c.kick()
将self改为其他变量名tt不影响结果
class Ball:
def __init__(self,name):
self.name=name
def kick(self):
print('我是%s,该死的,谁踢我...'%self.name)
b=Ball('土豆')
b.kick()
c=Ball('黄瓜')
c.kick()
注意:_init__(self,name)这个构造函数的左右下划线都是两个。固定格式,不然会报错TypeError: object() takes no parameters 类型错误:对象不接受参数。
前后对比发现是直接调用Ball的,相当于类Ball的自身函数。__init__()是类的构造函数,在建立对象时调用。self是对“对象”自身的引用。内部函数调用,用于初始化对象。
class Ball:
def __init__(tt,name):
tt.name=name
def kick(tt):
print('我是%s,该死的,谁踢我...'%tt.name)
b=Ball('土豆')
b.kick()
c=Ball('黄瓜')
c.kick()
把self换成其他变量名发现结果不变?
那改与不改究竟有撒区别呢?请理论+实例讲解下。
class Person:
name='小甲鱼'
p=Person()
print(p.name)
class Person:
__name='小甲鱼'
p=Person()
print(p._Person__name)
参考http://blog.csdn.net/doufei_c... http://blog.csdn.net/gudeshen...
懂Python的朋友都知道Python把以两个或以上下划线字符开头且没有以两个或以上下划线结尾的变量当作私有变量。私有变量会在代码生成之前被转换为长格式(变为公有)。转换机制是这样的:在变量前端插入类名,再在前端加入一个下划线字符。这就是所谓的私有变量轧压(Private name mangling)。如类A里的__private标识符将被转换为_A__private,这就是上一节出现_A__private和__private消失的原因了。
Python为了保证不能再class之外访问该变量,,Python会在类的内部自动的把你定义的__spam变量的名字替换成为 _classname__spam(注意,classname前面是一个下划线,spam前是两个下划线),Python把这种技术叫做“name mangling”。因此,用户在外部访问__spam的时候就会提示找不到相应的变量。
解释下用途 区别
What are you asking? I don’t quite understand~
Never visit like that. The tutorial is just to tell you how the underlying implementation is implemented
http://greybeard.iteye.com/bl...
http://python3-cookbook.readt...
These two links may answer your questions
Special variable naming
1. _xx starting with a single underscore represents a protected type variable. That is, a protected type can only allow access by itself and subclasses. If internal variables are marked, such as: When using "from M import", objects starting with an underscore will not be imported.
2. __xx double underscores represent private type variables. Only the class itself is allowed to be accessed. Even subclasses cannot be used to name a class attribute (class variable). The name is changed when called (inside class FooBar, __boo becomes _FooBar__boo, such as self._FooBar__boo)
3. __xx__ defines special methods. Variables or attributes in user-controlled namespaces, such as init, __import__ or file. Use only when documented, do not define such variables yourself. (That is to say, these are variable names defined internally in python)