Python: how to "new" a class instance and set its properties when in passing argument?
Python code:
class A:
'''omitted'''
pass
def foo(A): pass
a = A()
a.xx = 1
a.yy = 2
foo(a)
is it possible to rewrite above code like this?
foo(a = A(), a.xx =1, a.bb = 2)
Thanks!
===================
thanks for the solutio开发者_如何学编程n below:
foo(A())
but if A has foo1(), foo2()
a = A()
a.foo1()
a.foo2()
foo(a)
how can above code be coded looks like:
foo(a = A(); a.foo1(); a.foo2())
?
Thanks again
You mean a constructor? You just need to supply an __init__
method:
class A(object):
def __init__(self, xx, yy):
self.xx = xx
self.yy = yy
foo(A(1, 2))
If you're that dead set against calling foo1 and foo2 in or before the function foo, call it in the __init__
that @Santa crafted for you like.
class A(object):
def __init__(self, xx=None, yy=None):
self.xx = xx
self.yy = yy
self.foo1()
self.foo2()
def foo1(self):
"""
Do something here
"""
def foo2(self):
"""
Do something else here
"""
foo(A(1,2))
foo(A())
You're now passing the function foo the object A with properties set and methods called.
Sorry, but if you are writing Python you will have to use Python syntax. An assignment in Python is not an expression so if you want to assign to something you write it as a separate statement.
a = A()
a.foo1()
a.foo2()
foo(a)
Is correct, clear and succinct.
Short answer: you can't!
Long answer:
foo(a = A(), a.xx =1, a.bb = 2)
This syntax suggests that foo is a callable, with commas separating positional or keyword arguments. Since you put equals signs, it must be keyword args but a.xx is not a valid keyword name
foo(a = A(); a.foo1(); a.foo2())
; is not a valid argument separator
精彩评论