简体   繁体   English

Python-如何在不创建对象的情况下使用属性

[英]Python - How use properties without creating an object

How do I write a class to make this code work. 我如何编写一个类使此代码起作用。

class number:

    def double(self):
        return n*2

print(number(44).double)
>> 88

Well, you could decorate the number.double method with property : 好了,您可以用property装饰number.double方法:

class number:
    def __init__(self, number):
        self.number = number
    @property
    def double(self):
        return self.number * 2


print(number(42).double) # 84

If you know the type of your argument, it'd be better to inherit number from it. 如果您知道参数的类型,则最好继承它的number For example 例如

class number(int):
    @property
    def double(self):
        return type(self)(self * 2)

print(number(42).double) # 84
print(number(42).double.double) # 168

Here you are: 这个给你:

class Number(object):

    def __init__(self, n):
        self.n = n

    def double(self):
        return 2*self.n

print(Number(44).double())

A couple of notes: 一些注意事项:

  1. Since double() is a method of the class Number (and not an attribute), you need to use parentheses to call it. 由于double()Number类(而不是属性)的方法,因此需要使用括号来调用它。
  2. In Python it's considered standard practice to give classes uppercase names. 在Python中,为类提供大写名称被视为标准做法。
  3. If you want to define an instance variable (in this case n , or 44 , you must def the __init__() function which gives the interpreter instructions for how to create, or initialize an instance of your class. 如果要定义一个实例变量(在这种情况下n ,或44 ,则必须def__init__()函数,它给出了如何创建或初始化类的实例解释说明。

Hope this helps, and good luck! 希望这会有所帮助,并祝你好运!

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

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