Oct-03-2021, 04:56 PM
Oct-03-2021, 05:03 PM
def common_func(text): print(text) class AClass: def multiple_method1(salf): common_func("multiple_method1") def multiple_method2(salf): common_func("multiple_method2")
Oct-03-2021, 06:31 PM
ah, outside the class, in the module. i was putting them inside the class (was the only class, anyway). Thanks!
Oct-03-2021, 07:30 PM
Could make it a static method of the class as well if it would be better to keep it in the class.
Oct-03-2021, 07:48 PM
Oct-03-2021, 11:13 PM
(Oct-03-2021, 07:48 PM)Yoriz Wrote: [ -> ]Yes, that is what you asked for a function, not a method.yes, that was for something most of the methods needed to call to avoid redundant code i was changing for various tests.
and now i am thinking back on this. it has been my understanding that a def somewhere creates a function and that a def inside a class make that function be referenced in that class' methods table. does it work some other way?
it has also been my understanding the functions def'd somewhere will see the scope they are def'd in as their global space. but then classes have been a mystery because of two spaces.
Oct-04-2021, 12:44 AM
(Oct-03-2021, 11:13 PM)Skaperen Wrote: [ -> ]it has been my understanding that a def somewhere creates a function and that a def inside a class make that function be referenced in that class' methods table. does it work some other way?It dos not work the way you explain here.
To explain a little that may clear it up.
If want a function inside class then need to use
@staticmethod
,just a def
inside a class make no sense and don't work.What's make
def
a method is the use of self
.The reason to use
staticmethod
is if you have something that could be written as a standalone function (not part of any class),but you want to keep it within the class because it's somehow semantically related to the class.
import math class AClass: def foo(self): '''A method because of self''' return 42 @staticmethod def circle_area(r): ''' A normal function knows nothing about the class or instance It's still bound to the class and can be called ''' return r ** 2 * math.pi def bar(): '''Make no sense and should not be here''' return 99Usage:
>>> # Do not require a class instance creation >>> AClass.circle_area(5) 78.53981633974483 >>> >>> obj = AClass() >>> obj.foo() 42 >>> obj.circle_area(5) 78.53981633974483 >>> obj.bar() Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: bar() takes 0 positional arguments but 1 was given
Oct-04-2021, 07:07 PM
tuzen takk
i knew my knowledge of classes was off, but i did not know exactly where.
i knew my knowledge of classes was off, but i did not know exactly where.