[英]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: 一些注意事项:
double()
is a method of the class Number
(and not an attribute), you need to use parentheses to call it. double()
是Number
类(而不是属性)的方法,因此需要使用括号来调用它。 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.