在__init__内部或外部的类中实例化一个类有什么区别?

时间:2018-03-28 04:13:00

标签: python python-2.7

更清楚:在这个例子中,“再见”和“再见”之间有什么区别吗?一个人比另一个人有任何优势吗?

class Hello(object):

    def hi(self):
        pass

class Goodbye(object):

    def __init__(self):
        self.hello = Hello()

class Farewell(object):

    hello = Hello()

2 个答案:

答案 0 :(得分:0)

是。 Goodbye类和Farewell类之间的区别在于Goodbye具有实例成员 hello,而Farewell类有一个类成员 hello。如果您更改属于Hello对象的Farewell类,那么 Farewell的所有实例都会看到更改,因此您可以执行此操作:

a = Goodbye()
b = Goodbye()

a.hello.member = 1 # monkey-patching the member
b.hello.member = 2

print(a.hello.member) # prints "1"
print(b.hello.member) # prints "2"

f = Farewell()
g = Farewell()

f.hello.member = 1
g.hello.member = 2

print(f.hello.member) # prints "2"!

这是有效的原因是因为,正如您所定义的那样,Goodbye类的实例具有自己的Hello对象实例,而Farewell类的所有实例共享相同的Hello对象。查看the documentation了解详情!

现在,一个人是否拥有另一个优势是依赖于实现的。类成员有时可能会混淆那些可能希望类的不同实例独立于其他操作保留自己的状态的用户(即,可变类成员可以中断encapsulation。)但是,从效率点开始它可能是有用的定义在所有类中保持不变的成员的视图(确保以某种方式向用户注意这一点,比如将它们隐藏在下划线前缀或明确的文档后面)。

答案 1 :(得分:0)

考虑以下示例:

@IBOutlet weak var viewOn: UIView!

let animationView = LOTAnimationView(name: "restless_gift_ii") {
animationView.loopAnimation = true
animationView.contentMode = .scaleToFill
animationView.animationSpeed = 1
animationView.backgroundColor = UIColor.black
animationView.frame.size = viewOn.frame.size
animationView.center.x = viewOn.center.x
animationView.center.y = viewOn.center.y
viewOn.addSubview(animationView) }
构造该类的对象时,将调用

__ init__。所以你不会看到文字"这是再见的文字"直到你创建一个Goodbye()对象(类似class Hello(object): def hi(self): print("Hello") class Goodbye(object): def __init__(self): self.hello = Hello() print("this is the Goodbye text") class Farewell(object): hello = Hello() print("this is the Farewell text") )。但是,你会看到"这是告别文本"当你运行包含告别类的python脚本时,你将看不到"这是告别文本"当你创建一个告别类的对象时。

相关问题