简体   繁体   English

如何在python中定义没有默认值的类属性

[英]How to define a class attribute with no default value in python

I'm a C# developer learning python. 我是一名C#开发人员学习python。

If I want to define a class with certain attributes, but not provide default values for the attributes, how is that done? 如果我想定义一个具有某些属性的类,但不为属性提供默认值,那该怎么办?

For example (this is my best guess of how to do it): 例如(这是我最好的猜测方法):

class Spam
    eggs = None
    cheese = None

Or, is this legal: 或者,这是合法的:

class Spam
    eggs
    cheese

Or something else? 或者是其他东西?

You don't. 你没有。 You assign to the attributes later on, or set them to None . 您稍后分配属性,或将它们设置为None

An attribute without a value is not an attribute. 没有值的属性不是属性。 Being dynamic, it's perfectly fine to assign the attribute later on without having to declare it in the class. 作为动态,稍后分配属性是完全正确的,而不必在类中声明它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM