クラス変数
- クラスオブジェクトが持つ変数。たとえば
Apple
クラスのオブジェクトap01
が持っているap01.color
はインスタンス変数。Apple.color
がクラス変数。
特殊メソッド
object
クラスが持つメソッド。これをオーバーライドすることで、たとえばクラス間で四則演算や比較演算などが可能。
is
- 前後のオブジェクトが同一のオブジェクトならTrueを返す。
チャレンジ
1
>>> class Square:
... square_list = []
... def __init__(self, x):
... self.x = x
... self.square_list.append(x)
...
>>> a = Square(2)
>>> b = Square(4)
>>> c = Square(6)
>>> Square.square_list
[2, 4, 6]
>>> a.square_list
[2, 4, 6]
>>>
2
>>> class Square:
... def __init__(self,x):
... self.x = x
... def __repr__(self):
... return "{} by {} by {} by {}".format(self.x,self.x,self.x,self.x)
...
>>> a = Square(2)
>>> print(a)
2 by 2 by 2 by 2
3
>>> def is_eq(x,y):
... return x is y
...
>>> a = "hoge"
>>> b = a
>>> is_eq(a,b)
True
>>> b = "fuga"
>>> is_eq(a,b)
False
>>>