栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

传递变量,创建实例,自我,类的机制和用法:需要说明

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

传递变量,创建实例,自我,类的机制和用法:需要说明

class Foo (object):
# ^class name #^ inherits from object

    bar = "Bar" #Class attribute.    def __init__(self):        #        #^ The first variable is the class instance in methods.          #        #  This is called "self" by convention, but could be any name you want.        #^ double underscore (dunder) methods are usually special.  This one         #  gets called immediately after a new instance is created.        self.variable = "Foo" #instance attribute.        print self.variable, self.bar  #<---self.bar references class attribute        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute        print self.variable, self.bar    def method(self, arg1, arg2):        #This method has arguments.  You would call it like this:  instance.method(1, 2)        print "in method (args):", arg1, arg2        print "in method (attributes):", self.variable, self.bara = Foo() # this calls __init__ (indirectly), output:      # Foo bar      # Foo  Bar is now Bazprint a.variable # Fooa.variable = "bar"a.method(1, 2) # output:    # in method (args): 1 2    # in method (attributes): bar  Bar is now BazFoo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.class Bar(object):    def __init__(self, arg):        self.arg = arg        self.Foo = Foo()b = Bar(a)b.arg.variable = "something"print a.variable # somethingprint b.Foo.variable # Foo


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516738.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号