python 实例方法看到实例变量_python中的实例方法、静态方法、类方法、类变量和实例变量...

class MyTest:

myname = 'peter'

# add a instance attribute

def __init__(self, name):

self.name = name

# class access class attribute

def sayhello(self):

print "say hello to %s" % MyTest.myname

# instance can access class attribute

def sayhello_1(self):

print "say hello to %s" % self.myname

# It's a snap! instance can access instance attribute

def sayhello_2(self):

print "say hello to %s" % self.name

# class can not access instance attribute!!!

def sayhello_3(self):

#print "say hello to %s" % MyTest.name

pass

if __name__ == '__main__':

test = MyTest("abc")

test.sayhello()

test.sayhello_1()

test.sayhello_2()

test.sayhello_3()

# class's definition can be changed dynamically

MyTest.yourname = "Allen"

print MyTest.myname

print MyTest.yourname

---------------------------------------------------------------------------------------------------------------------

class Foo:

def func(self):

print "object method"

@classmethod

def cfunc(cls):

print "class method"

@staticmethod

def sfunc(a, b):

print "static method:", a, " + ", b, "=", a + b

if __name__ == '__main__':

foo = Foo()

# instance method can be called by object and class name

foo.func()

Foo.func(foo)

# both instance and class can call class method

foo.cfunc()

Foo.cfunc()

# both instance and class can call static method

Foo.sfunc(10, 20)

foo.sfunc(50, 100)

----------------------------------------------------------------------------------------------------------------------

注

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值