简体   繁体   English

关于类变量和实例变量? (Python)

[英]About class variables and instance variables? (Python)

I have this code that adds 10 to either the variable x or y but it also has a method that prevents those values to go above 100 or below 0. The program asks for user input about which value to increment either x or y values:我有这段代码将变量 x 或 y 加 10,但它也有一种方法可以防止这些值超过 100 或低于 0。该程序要求用户输入关于增加 x 或 y 值的值:

class X_increment(object):

     x=0
     y=0

     def x_y(self,min=0,max=100):

        if self.x<=min:
            self.x=0
        elif self.x>=max:
            self.x=100

        if self.y<=min:
            self.y=0
        elif self.y>=max:
            self.y=100



x1=X_increment()
x2=X_increment()

while (True):

  z=input("Press x to increase x")

  if z=='x':
    x1.x+=10
    x1.y-=5
    x1.x_y()
    print(x1.x,x1.y)

  elif z=='y':
    x1.y+=10
    x1.x-=5
    x1.x_y()
    print(x1.x,x1.y)

  elif z=='e':
    break

  else:
    print("not valid")

print("the value of x and y is:",x1.x,x1.y)
print("the value of x and y of the x2 instance is",x2.x,x2.y)

I was using it to test how to modify values of an instance and it worked, but i tried the same code but initializing the variables like this:我用它来测试如何修改实例的值并且它起作用了,但我尝试了相同的代码,但初始化变量如下:

def __init__(self):

    x=0
    y=0

And it didn't work, i tried it calling the variables in multiple ways but it just didn't work so i figured there is something i was doing wrong or maybe you can't change variables in a "constructor" like i am tryingto do?, i don't know, i am pretty new to programming and python and i really get confused by this.它没有用,我尝试以多种方式调用变量,但它没有用,所以我想我做错了什么,或者你不能像我试图那样在“构造函数”中更改变量做?,我不知道,我对编程和 python 很陌生,我真的对此感到困惑。

When you declare attributes in the class definition, like当您在类定义中声明属性时,例如

class X_increment(object):
    x = 0
    y = 0

x and y are attributes of the class object X_increment . xy是类对象X_increment属性。 When you access them on an instance like x1 = X_increment() , x1.x , the attribute lookup fails on the instance x1 , then goes up to the class object, where it finds it.当您访问他们的实例像x1 = X_increment() x1.x ,属性查找失败的实例x1 ,然后上升到类对象,在那里找到它。 Incidentally, since x and y are class attributes, x1 and x2 share x and y (ie, x1.x and x2.x refer to the same value).顺便说一下,由于xy是类属性,因此x1x2共享xy (即, x1.xx2.x指代相同的值)。

When you declare the attributes in __init__ , you need to explicitly set them on the instance you're creating:当您在__init__声明属性时,您需要在正在创建的实例上显式设置它们:

class X_increment(object):
    def __init__(self):
        self.x = 0
        self.y = 0

The reason you can't simply do x = 0 anymore is that the __init__ function isn't executing in the class body, so as soon as the function is finished the local variables x and y would vanish.你不能再简单地做x = 0的原因是__init__函数没有在类体中执行,所以一旦函数完成,局部变量xy就会消失。 Once you've defined __init__ this way, things should work as expected: each instance ( x1 and x2 ) has its own values of x and y .以这种方式定义__init__ ,事情应该会按预期工作:每个实例( x1x2 )都有自己的xy值。 self is a reference to the individual instance you're calling the method on. self是对调用方法的单个实例的引用。

You may also be interested in properties , which are a more general and powerful way of writing your x_y method.您可能还对properties感兴趣,这是编写x_y方法的更通用和更强大的方法。

The difference between a class variable and an instance variable is that the class variable doesn't need an instance to be accessed.类变量和实例变量之间的区别在于类变量不需要访问实例。 In the following example, I declare and use class variables:在以下示例中,我声明并使用了类变量:

class Test:
    classVariable = 5

#no need to create an instance of the class
print(Test.classVariable) #prints 5
Test.classVariable = 10
print(Test.classVariable) #prints 10

Whereas an instance variable can have a different value on each instance that has been created:而实例变量可以在每个已创建的实例上具有不同的值:

class Test:
    def __init__(self):
        self.instanceVariable = 0;

#creating 2 instances of the same class
instance1 = Test()
instance2 = Test()

#they start with the same value
print("1=%s, 2=%s" % (instance1.instanceVariable, instance2.instanceVariable))
#prints "1=0, 2=0"

#but we can modify the value on each instance separatly
instance1.instanceVariable = 5;
print("1=%s, 2=%s" % (instance1.instanceVariable, instance2.instanceVariable))
#prints "1=5, 2=0"

print(Test.instanceVariable) #this won't work

Variables declared outside functions in a class are class variables.在类中的函数外部声明的变量是类变量。 Instance variables can be declared several ways, one of them is using self.xxx in the constructor or other functions可以通过多种方式声明实例变量,其中一种是在构造函数或其他函数中使用self.xxx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM