成员变量和python中的实例属性是一样的吗?

2024-09-24 00:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

在pythonwiki中,属性被描述为方法中定义的变量,在这个链接中:http://pythoncentral.io/introduction-to-python-classes/它们将下面代码中的val描述为成员变量。你知道吗

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

我只是想知道这是否也意味着val是一个实例属性(或者可能是一个class属性,因为它是在init部分中定义的)?抱歉,如果这是一个重复的问题,但我找不到任何证实这一点。你知道吗


Tags: to方法ioselfhttp属性定义init
1条回答
网友
1楼 · 发布于 2024-09-24 00:28:50

实例/成员变量是与类的特定实例关联的值。对于每个类,这些方法可能不同,并且可以通过类方法进行访问。类变量是在类的每个实例中原本相同的东西。例如,以以下类文件为例:

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

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

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!!!

现在,由于实例变量是使用uu2;声明为私有的,因此通常不会直接修改这些变量,而是使用属性来提供允许修改这些变量的方法。这些方法允许您添加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

相关问题 更多 >