2016-06-19 61 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

相關問題