2016-06-19 38 views
0

在python wiki中,属性被描述为方法中定义的变量,并且在这个链接中:http://pythoncentral.io/introduction-to-python-classes/他们将下面代码中的val描述为成员变量。成员变量是否与python中的实例属性相同?

class Foo: 
     def __init__(self, val): 
      self.val = val 
     def printVal(self): 
      print(self.val) 

我只是想知道,如果这也意味着,VAL是一个实例属性(或者一个类的属性,因为它是在初始化部分定义?很抱歉,如果这是一个重复的问题,但我不能” t找到任何证实这一点的东西

+0

实例属性是指一类的特定实例,其中可以有许多的属性。类属性是指类本身的属性,它们由实例继承,但在类中定义(除非在实例中被重写)。 –

回答

1

实例/成员变量是与一个类的特定实例相关联的值,对于每个类可以是不同的,并且可以通过类方法访问。例如,采取以下类文件:

class MyClass(object): 
    class_variable = "!" 

    def __init__(self, first_word, second_word): 
     self.__instance_variable_one = first_word 
     self.__instance_variable_two = second_word 

    def to_string(self): 
     return self.__instance_variable_one + " " + self.__instance_variable_two 

请注意,这里的实例变量带有__前缀,表示这些应该是私有的。现在使用这个类:

object_instance_one = MyClass("Hello", "World") 
object_instance_one.to_string() 

Hello World

print object_instance_one.class_variable 

!

注意,这是直接访问的类变量,而不是通过一个方法。

print object_instance_one.to_string() + object_instance_one.class_variable 

Hello World!

您可以覆盖类变量,如果你想:

object_instance_one.class_variable = "!!!" 
print object_instance_one.to_string() + object_instance_one.class_variable 

Hello World!!!

现在因为实例变量使用__声明为private,你通常不会直接而是修改这些使用属性来提供允许您修改这些的方法。这些正确的方法允许您添加setter和getter方法(例如验证或类型检查)。一个例子:

class MyClass(object): 
class_variable = "!" 

def __init__(self, first_word=None, second_word=None): 
    self.__instance_variable_one = first_word 
    self.__instance_variable_two = second_word 

@property 
def instance_variable_one(self): 
    return self.__instance_variable_one 

@instance_variable_one.setter 
def instance_variable_one(self, value): 
    if isinstance(value, str): 
     self.__instance_variable_one = value 
    else: 
     raise TypeError("instance variable one must be of type str") 

@property 
def instance_variable_two(self): 
    return self.__instance_variable_two 

@instance_variable_two.setter 
def instance_variable_two(self, value): 
    if isinstance(value, str): 
     self.__instance_variable_two = value 
    else: 
     raise TypeError("instance variable two must be of type str") 

def to_string(self): 
    return str(self.__instance_variable_one) + " " + str(self.__instance_variable_two) 

用法:

object_instance_one = MyClass() 
object_instance_one.instance_variable_one = "Hello" 
object_instance_one.instance_variable_two = "World" 
print object_instance_one.to_string() + object_instance_one.class_variable 

Hello World!

object_instance_one.instance_variable_two = 2 

File "C:/MyClass.py", line 38, in
object_instance_one.instance_variable_two = 2 File "C:/MyClass.py", line 28, in > >instance_variable_two raise TypeError("instance variable two must be of type str") TypeError: instance variable two must be of type str

相关问题