__slots__Python中的目的是什么- 特别是关于我何时想要使用它,何时不想使用它?
我已经读过可以在Python中向现有对象(即,不在类定义中)添加方法.
我知道这样做并不总是好事.但是人们怎么可能这样做呢?
我这样做:
def set_property(property,value):
def get_property(property):
Run Code Online (Sandbox Code Playgroud)
要么
object.property = value
value = object.property
Run Code Online (Sandbox Code Playgroud)
我是Python的新手,所以我还在探索语法,我想对此做一些建议.
在python中,我可以使用@classmethod装饰器向类添加方法.是否有类似的装饰器向类中添加属性?我可以更好地展示我在说什么.
class Example(object):
the_I = 10
def __init__( self ):
self.an_i = 20
@property
def i( self ):
return self.an_i
def inc_i( self ):
self.an_i += 1
# is this even possible?
@classproperty
def I( cls ):
return cls.the_I
@classmethod
def inc_I( cls ):
cls.the_I += 1
e = Example()
assert e.i == 20
e.inc_i()
assert e.i == 21
assert Example.I == 10
Example.inc_I()
assert Example.I == 11
Run Code Online (Sandbox Code Playgroud)
我上面使用的语法是可能的还是需要更多的东西?
我想要类属性的原因是我可以延迟加载类属性,这似乎足够合理.
我有这个代码:
class A(object):
@staticmethod
def open():
return 123
@staticmethod
def proccess():
return 456
switch = {
1: open,
2: proccess,
}
obj = A.switch[1]()
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我不断收到错误:
TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
怎么解决?
几个月前我刚刚开始学习Python,我试图理解不同__get*__方法之间的差异:
__get__
__getattr__
__getattribute__
__getitem___
Run Code Online (Sandbox Code Playgroud)
他们的__del*__等价物:
__del__
__delattr__
__delete__
__delitem__
Run Code Online (Sandbox Code Playgroud)
这些有什么区别?我什么时候应该使用另一个?是否有一个特定的原因,为什么大多数__get*__方法都有__set*__等价物,但没有__setattribute__?
正如标题所说.
来自Java我以前用过:
private int A;
public void setA(int A) {
this.A = A;
}
public int getA() {
return this.A
}
Run Code Online (Sandbox Code Playgroud)
我如何在Python中执行此操作(如果需要).如果其中之一__setattr__或__set__用于此目的,另一个用于什么?
编辑:我觉得我需要澄清一下.我知道在Python中,一个doe不会在需要之前创建setter和getter.
让我们说我想做这样的事情:
public void setA(int A) {
update_stuff(A);
and_calculate_some_thing(A);
this.A = A;
}
Run Code Online (Sandbox Code Playgroud)
什么是"pythonic"方式来实现这个?
请参阅下面的简单示例:
class Celsius(object):
def __init__(self, value=0.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
def __call__(self):
print('__call__ called')
class Temperature(object):
celsius = Celsius()
def __init__(self):
self.celsius1 = Celsius()
T = Temperature()
print('T.celsius:', T.celsius)
print('T.celsius1:', T.celsius1)
output
T.celsius: 0.0
T.celsius1: <__main__.Celsius object at 0x023544F0>
Run Code Online (Sandbox Code Playgroud)
我想知道为什么他们有不同的输出.我知道T.celsius会打电话给__get__并T.celsius1致电__call__.
我正在编写一个使用内省找到类的"未绑定方法"的代码,并且惊讶地发现内置类型有两种不同的描述符:
>>> type(list.append), list.append
(<class 'method_descriptor'>, <method 'append' of 'list' objects>)
>>> type(list.__add__), list.__add__
(<class 'wrapper_descriptor'>, <slot wrapper '__add__' of 'list' objects>)
Run Code Online (Sandbox Code Playgroud)
搜索文档非常有限但有趣的结果:
inspect.getattr_static它不解析描述符并包含可用于解析它们的代码.method_descriptor是更有效的比wrapper_descriptor,但是不解释它们是什么:
的方法
list.__getitem__(),dict.__getitem__()和dict.__contains__()现在被实现为method_descriptor对象,而不是wrapper_descriptor对象.这种访问形式使其性能翻倍,并使它们更适合用作功能的参数:map(mydict.__getitem__, keylist).
性能上的差异引起了我的兴趣,显然存在差异所以我去寻找其他信息.
这些类型都不在模块中types:
>>> import types
>>> type(list.append) in vars(types).values()
False
>>> type(list.__add__) in vars(types).values()
False
Run Code Online (Sandbox Code Playgroud)
使用help不提供任何有用的信息:
>>> help(type(list.append))
Help …Run Code Online (Sandbox Code Playgroud) 所以,我已经知道字符串有一个中心方法.
>>> 'a'.center(3)
' a '
Run Code Online (Sandbox Code Playgroud)
然后我注意到我可以使用'str'对象做同样的事情,这是一种类型,因为
>>> type(str)
<type 'type'>
Run Code Online (Sandbox Code Playgroud)
使用这个'type'对象,我可以访问字符串方法,就像它们是静态函数一样.
>>> str.center('a',5)
' a '
Run Code Online (Sandbox Code Playgroud)
唉! 这违反了蟒蛇的禅宗.
应该有一个 - 最好只有一个 - 明显的方法来做到这一点.
甚至这两种方法的类型也不同.
>>> type(str.center)
<type 'method_descriptor'>
>>> type('Ni!'.center)
<type 'builtin_function_or_method'>
Run Code Online (Sandbox Code Playgroud)
现在,
谢谢你的回答!
python ×10
oop ×2
accessor ×1
attributes ×1
class-method ×1
methods ×1
properties ×1
slots ×1
string ×1