# zfill Python中的靜態方法?

## zfill in python (7)

``````ClassName.StaticMethod ( )
``````

``````[email protected]:/home/jeffs  \$ python36
Python 3.6.1 (default, Sep  7 2017, 16:36:03)
[GCC 6.3.0 20170406] on linux
>>> import cmath
>>> print(cmath.sqrt(-4))
2j
>>>
>>> dir(cmath)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
>>>
``````

（請注意，這個答案是指Python 3.x.在Python 2.x中，你會得到一個`TypeError`來調用類本身的方法。）

``````class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable

def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)

def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))

def rollCall(n): #this is implicitly a class method (see comments below)
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print("  {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))

fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
``````

``````rex.rollCall(-1)
``````

``````@staticmethod
``````

``````rex.rollCall(-1)
``````

``````class Dog:
count = 0 # this is a class variable
dogs = [] # this is a class variable

def __init__(self, name):
self.name = name #self.name is an instance variable
Dog.count += 1
Dog.dogs.append(name)

def bark(self, n): # this is an instance method
print("{} says: {}".format(self.name, "woof! " * n))

@staticmethod
def rollCall(n):
print("There are {} dogs.".format(Dog.count))
if n >= len(Dog.dogs) or n < 0:
print("They are:")
for dog in Dog.dogs:
print("  {}".format(dog))
else:
print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))

fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
rex.rollCall(-1)
``````

``````class MyClass(object):
@staticmethod
def the_static_method(x):
print x

MyClass.the_static_method(2) # outputs 2
``````

``````class MyClass(object):
def the_static_method(x):
print x
the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2) # outputs 2
``````

``````class C:
@staticmethod
def f(arg1, arg2, ...): ...
``````

@staticmethod表單是一個函數decorator - 有關詳細信息，請參閱函數定義中函數定義的描述。

Python中的靜態方法類似於Java或C ++中的方法。 有關更高級的概念，請參見`classmethod()`

2.2版本中的新功能。

``````>>> class C:
...     @staticmethod
...     def hello():
...             print "Hello World"
...
>>> C.hello()
Hello World
``````

``````class Dog(object):
def __init__(self, name):
self.name = name

def bark(self):
if self.name == "Doggy":
return barking_sound()
else:
return "yip yip"

def barking_sound():
return "woof woof"
``````

``````# garden.py
def trim(a):
pass

def strip(a):
pass

def bunch(a, b):
pass

def _foo(foo):
pass

class powertools(object):
"""
Provides much regarded gardening power tools.
"""
@staticmethod
return 42

@staticmethod
def random():
return 13

@staticmethod
def promise():
return True

def _bar(baz, quux):
pass

class _Dice(object):
pass

class _6d(_Dice):
pass

class _12d(_Dice):
pass

class _Smarter:
pass

class _MagicalPonies:
pass

class _Samurai:
pass

class Foo(_6d, _Samurai):
pass

class Bar(_12d, _Smarter, _MagicalPonies):
pass
``````

...

``````# tests.py
import unittest
import garden

class GardenTests(unittest.TestCase):
pass

class PowertoolsTests(unittest.TestCase):
pass

class FooTests(unittest.TestCase):
pass

class BarTests(unittest.TestCase):
pass
``````

...

``````# interactive.py
from garden import trim, bunch, Foo

f = trim(Foo())
bunch(f, Foo())
``````

...

``````# my_garden.py
import garden
from garden import powertools

class _Cowboy(garden._Samurai):
def hit():
return powertools.promise() and powertools.random() or 0

class Foo(_Cowboy, garden.Foo):
pass
``````

``````# utils.py
class socket(object):
@staticmethod
def check_if_port_available(port):
pass

@staticmethod
def get_free_port(port)
pass

class image(object):
@staticmethod
def to_rgb(image):
pass

@staticmethod
def to_cmyk(image):
pass
``````