Defining a Python class with lots of attributes - style
我有一个具有许多属性的类。有人能解释一下下面的a、b、c和x、y、z等设置属性之间的区别吗?我明白,如果要输入参数,它们显然必须在init中,但是,只是为了设置一个数字默认变量,这是首选的,利弊是什么。
1 2 3 4 5 6 7 8 | class Foo(object): a = 'Hello' b = 1 c = False def __init__(self): self.x = 'World' self.y = 2 self.z = True |
(P)字母名称0,字母名称1,字母名称2他们是评估和第十一期,当阶级是第一次创造。变量EDOCX1的英文字母3,EDOCX1的英文字母4,和EDOCX1的英文字母5,是瞬息万变的,它是评估和安排当一个目标的类别是瞬息万变的。(p)(P)总的来说,如果同一价值观要由分类中的每一个瞬间使用,你使用的分类变量是11。You use instance variables for variables that are going to be different for each instance of that class.(p)(P)You can access class variables through the instance variable syntax EDOCX1 general 6,but the object in question is being shared between all instances of the class.This doesn't affect much when using immutable data types such as integers or strings,but when using mutable data types such as lists,appending to EDOCX1 disciplinary 6.Would cause all instances to see the newly-appended value.(p)(P)从IDLE得到的一些实例可能有助于理解这一点:(p)字母名称
(P)The main con/gotcha with using class attributes to provide default values for what you intend to be instance-specific data is that the default values are going to be shared between all instances of the class until the value is changed.E.G.(p)字母名称(P)However,the following will work as one might expect:(p)字母名称(P)To avoid this gotcha while using this technique,you should only use it to set default that are immutable values.(e.g.numbers,strings,tuples…)(p)(P)The reason why python behaves this way is that when you access an attribute with:(p)字母名称(P)Then EDOCX1 Only 13 Nicholic is first looked up in the object EDOCX1If the name in not found in the object(I.E.in EDOCX1 penalic 15),they the name is looked up in the type of that object.例如,这一机制是如何看待工作方法的一部分。(If you look at the EDOCX1 penal 16 of an object,you'll notice its methods Aren't there.)(p)(P)Other minor issues are that this exposes the defaults through the type object when they're intended to be instance-specific;and that it mixes the definitions of class-specific attributes(like constants)if you have any with the defaults.The corllary of the former is that this will let you redefine the value of the default later on for all objects that haven't changed the value yet by assigning to the class attribute.(This could be useful,or confusing;the same precaution against mutable"global"variables applies.)(p)
(P)As you've declared them,a,b,and c will be available without creating an instance of foo.例如,你可以说:(p)字母名称(P)In contrast,x,y,and z will not be created until you create an instance of foo,and they are specific to that instance:(p)字母名称
(P)这是你问的时代的问题(p)(P)EDOCX1 8 are class variables shared among all instances,a good use would be a counter to count all the occurrences of this class that have being created,EDOCX1 indicational 9.Are instance variables belonging to that single instance hence using EDOCX1(p)(P)注意你可以更新的暗影类变量像EDOCX1的英文11.This does not change EDOCX1的英文0.but rather shadows it.而且你在冲浪时抓了个丑八怪(p)(P)演示:(p)字母名称